package org.ycx.doc.web.controller;

import com.baidu.unbiz.fluentvalidator.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.ycx.common.enums.StatusEnum;
import org.ycx.common.validator.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.ycx.common.constants.RespCode;
import org.ycx.common.dto.RespMSG;
import org.ycx.doc.dao.enums.ModuleType;
import org.ycx.doc.dao.model.DocModule;
import org.ycx.doc.dao.model.DocModuleExample;
import org.ycx.doc.dao.model.DocModulePage;
import org.ycx.doc.dao.model.DocProject;
import org.ycx.doc.service.IDocModulePageService;
import org.ycx.doc.service.IDocModuleService;
import org.ycx.doc.service.IDocProjectService;
import org.ycx.upms.common.constants.SecurityConstants;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * DocModulecontroller
 * Created by yang on 2017-08-30 17:53:15.
 */
@Controller
@RequestMapping("/app/module")
public class DocModuleController {

    private static Logger _log = LoggerFactory.getLogger (DocModuleController.class);

    private static final String PRE = "module/";

    @Autowired
    private IDocModuleService service;

    @Autowired
    private IDocProjectService projectService;

    @Autowired
    private IDocModulePageService pageService;

    /**
     * 模块定义页面
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/{id}.html")
    public String indexPage(ModelMap modelMap, @PathVariable("id") Integer id) {
        DocModule module = this.service.selectByPrimaryKey (id);
        if (ModuleType.OnePage.getType () == module.getModuleType ()) {
            //简单页面
            modelMap.put ("moduleId", module.getModuleId ());
            return PRE + "page";
        } else {
            return "";
        }
    }

    /**
     * Ajax加载的文档内容(markdown)
     *
     * @param modelMap
     * @param id
     * @return
     */
    @RequestMapping("/{id}.md")
    @ResponseBody
    public RespMSG mdPage(ModelMap modelMap, @PathVariable("id") Integer id) {
        RespMSG resp = new RespMSG (RespCode.SUCCESS);
        DocModulePage page = this.pageService.selectByPrimaryKey (id);
        resp.setData (page.getContent ());
        return resp;
    }

    /**
     * 新增文档描述页面
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/create.html")
    public String createPage(ModelMap modelMap, Integer appId) {
        modelMap.put ("appId", appId);
        DocProject project = this.projectService.selectByPrimaryKey (appId);
        modelMap.put ("bean", project);
        return PRE + "create";
    }

    /**
     * 创建文件夹页面
     *
     * @param modelMap
     * @param appId
     * @return
     */
    @RequestMapping("/createDir.html")
    public String createDirePage(ModelMap modelMap, Integer appId) {
        modelMap.put ("appId", appId);
        DocProject project = this.projectService.selectByPrimaryKey (appId);
        modelMap.put ("bean", project);
        return PRE + "createDir";
    }

    /**
     * 更新页面
     *
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/update/{id}.html")
    public String updatePage(@PathVariable("id") int id, ModelMap modelMap) {
        DocModule bean = this.service.selectByPrimaryKey (id);
        DocProject project = this.projectService.selectByPrimaryKey (bean.getAppId ());
        modelMap.put ("module", bean);
        modelMap.put ("bean", project);
        if (ModuleType.OnePage.getType () == bean.getModuleType ()) {
            modelMap.put ("pages", this.pageService.selectByPrimaryKey (bean.getModuleId ()));
        }
        return PRE + "update";
    }

    /**
     * 更新页面
     *
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/detail/{id}.html")
    public String detailPage(@PathVariable("id") int id, ModelMap modelMap) {
        DocModule bean = this.service.selectByPrimaryKey (id);
        modelMap.put ("bean", bean);
        return PRE + "detail";
    }

    /**
     * 新增功能
     *
     * @param bean
     * @return
     */
    @RequestMapping(value = "/createPage", method = RequestMethod.POST)
    public String createOnePage(ModelMap modelMap, DocModule bean, String content, Integer appId,HttpSession session) {
        int uid = (int) session.getAttribute (SecurityConstants.CURRENT_UID);
        ComplexResult result = FluentValidator.checkAll ()
                .on (bean.getModuleName (), new NotNullValidator ("模块名称"))
                .doValidate ()
                .result (ResultCollectors.toComplex ());
        if (!result.isSuccess ()) {
            modelMap.put ("error", ValidationErrorToString.errorToString (result.getErrors (), "\n\r"));
            return createPage (modelMap, appId);
        } else {
            bean.setAppId (appId);
            bean.setCreateTs (new Date ());
            bean.setUpdateTs (new Date ());
            bean.setModuleCode (DigestUtils.md5Hex(content));
            bean.setStates (StatusEnum.OPEN.getKey ());
            bean.setCreateUid (uid);
            bean.setUpdateUid (uid);
            int count = this.pageService.addPage (bean, content);
            return "redirect:/project/" + appId + ".html";
        }
    }

    /**
     * 新增功能
     *
     * @param bean
     * @return
     */
    @RequestMapping(value = "/createDir", method = RequestMethod.POST)
    public String createDir(ModelMap modelMap, DocModule bean, Integer appId,HttpSession session) {
        int uid = (int) session.getAttribute (SecurityConstants.CURRENT_UID);
        ComplexResult result = FluentValidator.checkAll ()
                .on (bean.getModuleName (), new NotNullValidator ("模块名称"))
                .doValidate ()
                .result (ResultCollectors.toComplex ());
        if (!result.isSuccess ()) {
            modelMap.put ("error", ValidationErrorToString.errorToString (result.getErrors (), "\n\r"));
            return createPage (modelMap, appId);
        } else {
            bean.setAppId (appId);
            bean.setCreateTs (new Date ());
            bean.setUpdateTs (new Date ());
            bean.setModuleCode (DigestUtils.md5Hex(bean.getModuleName ()));
            bean.setModuleType (ModuleType.Dir.getType ());
            bean.setStates (StatusEnum.ALL.getKey ());
            bean.setmVersion (0);
            bean.setUpdateUid (uid);
            bean.setCreateUid (uid);
            int cou = this.service.insert (bean);
            return "redirect:/project/" + appId + ".html";
        }
    }

    /**
     * 更新功能
     *
     * @param id
     * @param bean
     * @return
     */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG update(@PathVariable("id") int id, DocModule bean, HttpSession session) {
        //TODO 验证数据，验证完成，设定主键为id
        ComplexResult result = FluentValidator.checkAll ()
                .on (bean.getModuleName (), new NotNullValidator ("模块名称"))
                .on (bean.getModuleCode (), new NotNullValidator ("模块唯一码"))
                .doValidate ()
                .result (ResultCollectors.toComplex ());
        if (!result.isSuccess ()) {
            RespMSG error = new RespMSG (RespCode.FAIL);
            error.setDesc (ValidationErrorToString.errorToString (result.getErrors (), "\n\r"));
            return error;
        }
        bean.setUpdateTs (new Date ());
        int count = service.updateByPrimaryKeySelective (bean);
        return new RespMSG (RespCode.SUCCESS);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @ResponseBody
    public RespMSG delete(@PathVariable("id") Integer id) {
        int count = service.deleteByPrimaryKey (id);
        return new RespMSG (RespCode.SUCCESS);
    }


    @RequestMapping("/list")
    @ResponseBody
    public RespMSG list(Integer appId, Integer type) {
        RespMSG resp = new RespMSG ();
        DocModuleExample beanExample = new DocModuleExample ();
        DocModuleExample.Criteria criteria = beanExample.createCriteria ().andAppIdEqualTo (appId);
        if (type != null) {
            criteria.andModuleTypeEqualTo (type);
        }
        List<DocModule> rows = this.service.selectByExample (beanExample);
        resp.initResp (RespCode.SUCCESS);
        resp.setData (rows);
        return resp;
    }

    @RequestMapping("/listShow")
    @ResponseBody
    public RespMSG listShow(Integer appId, Integer version) {
        RespMSG resp = new RespMSG ();
        List<DocModule> rows = this.service.selectByAppIdAndVersion (appId, version);
        resp.initResp (RespCode.SUCCESS);
        resp.setData (rows);
        return resp;
    }
}
